package com.xiaoxu.intranetweb.mybatisplusSzappdb.controller.statistics;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.JSONObject;

import java.net.URLEncoder;

import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.statistics.AggregateBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.statistics.MonthlyTrendBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.dao.UserInfoDao;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.CpyScoreExcelEn;
import com.xiaoxu.intranetweb.util.PermissionCheck;
import com.xiaoxu.intranetweb.util.SzResult;
import com.xiaoxu.intranetweb.util.WebFunctionUtil;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;

/**
 * 总览统计控制器
 *
 * @author xiaoxu
 * @version 1.0
 * @date 2023/2/1 15:00
 * @since 1.0
 */
@RestController
@RequestMapping(value = "/overview")
public class OverviewController {
    @Autowired
    private AggregateBu aggregateBu;
    @Autowired
    private MonthlyTrendBu monthlyTrendBu;
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private WebFunctionUtil webFunctionUtil;

    /**
     * 总出货量、总销售额、总出车量统计接口
     *
     * @return SzResult
     */
    @GetMapping("/aggregate")
    public SzResult aggregate(HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        //   if (!userInfoDao.getUserPermissionWeb(StpUtil.getLoginIdByToken(token).toString()).containsKey("plan_getAllPdtPlan")) {
        //            return SzResult.error("您没有查看发货计划的权限");
        //        }
        return aggregateBu.aggregate(token, plantId);
    }

    /**
     * 月度出货量统计接口
     *
     * @param year 年份
     * @return SzResult
     */
    @GetMapping("/monthlyWeightTrend")
    public SzResult monthlyWeightTrend(@RequestParam(value = "year", required = false) int year, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return monthlyTrendBu.monthlyWeightTrend(year, token, plantId);
    }

    /**
     * 月度销售额统计接口
     *
     * @param year 年份
     * @return SzResult
     */
    @GetMapping("/monthlyMoneyTrend")
    public SzResult monthlySalesTrend(@RequestParam(value = "year", required = false) int year, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return monthlyTrendBu.monthlyMoneyTrend(year, token, plantId);
    }

    /**
     * 年度各品种出货量统计接口
     *
     * @param year 年份
     * @return SzResult
     */
    @GetMapping("/annualWeightTrend")
    public SzResult yearlyProductWeightTrend(@RequestParam(value = "year", required = false) int year, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return monthlyTrendBu.annualWeightTrend(year, token, plantId);
    }

    /**
     * 年度各品种销售额统计接口
     *
     * @param year 年份
     * @return SzResult
     */
    @GetMapping("/annualMoneyTrend")
    public SzResult yearlyProductMoneyTrend(@RequestParam(value = "year", required = false) int year, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return monthlyTrendBu.annualMoneyTrend(year, token, plantId);
    }


    /**
     * 各公司年度物流占比
     */
    @GetMapping("/cpyYearLogistics")
    public SzResult cpyYearLogistics(@RequestParam(value = "cpy", required = false) String cpy, @RequestParam(value = "cpyChi", required = false) String cpyChi, @RequestParam(value = "year", required = false) String year, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return monthlyTrendBu.cpyYearLogistics(token, cpy, cpyChi, year, plantId);
    }

    /**
     * 各公司年度销售占比
     */
    @GetMapping("/cpyYearMoney")
    public SzResult cpyYearMoney(@RequestParam(value = "cpy", required = false) String cpy, @RequestParam(value = "cpyChi", required = false) String cpyChi, @RequestParam(value = "year", required = false) String year, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return monthlyTrendBu.cpyYearMoney(token, year, plantId);
    }

    /**
     * 各货物年度出货量占比
     */

    @GetMapping("/productYearWeight")
    public SzResult productYearWeight(@RequestParam(value = "year", required = false) String year, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return monthlyTrendBu.productYearWeight(token, year, plantId);
    }


    /**
     * 各货物年度收款占比
     */

    @GetMapping("/productYearMoney")
    public SzResult productYearMoney(@RequestParam(value = "year", required = false) String year, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return monthlyTrendBu.productYearMoney(token, year, plantId);
    }

    /**
     * 客户业绩考核表
     */
    @PostMapping("/cpyScore")
    @PermissionCheck("cpyScore")
    public SzResult cpyScore(@RequestBody JSONObject jsonParam, HttpServletRequest request) throws Exception {
        String timeStart = jsonParam.getString("timeStart");
        String timeEnd = jsonParam.getString("timeEnd");
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return monthlyTrendBu.cpyScore(token, timeStart, timeEnd, plantId);
    }

    /**
     * 客户业绩考核表导出excel
     */
    @PostMapping("/cpyScoreExcel")
    public void cpyScoreExcel(@RequestBody JSONObject jsonParam, HttpServletResponse response, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
//        if (!userInfoDao.getUserPermissionWeb(StpUtil.getLoginIdByToken(token).toString()).containsKey("cpyScore_exportExcel")) {
//            response.sendError(403,"您没有客户业绩考核表导出excel的权限");
//        }
        //        实体类
        List<Map<String, Object>> fields = jsonParam.getObject("fields", List.class);
//        文件名使用utf-8编码
        String filename = jsonParam.getString("filename");
//        数据
        List<Map<String, Object>> ids = jsonParam.getObject("ids", List.class);
//        是否有表头
        Boolean isHeader = jsonParam.getBoolean("isHeader");
//        mode为"current"时，导出当前页，为"all"时，导出所有页，selected时，导出选中数据
        String mode = jsonParam.getString("mode");
//        是否原始数据
        Boolean original = jsonParam.getBoolean("original");
//        分页
        Map<String, String> pager = jsonParam.getObject("pager", Map.class);
//        表格标题
        String sheetName = jsonParam.getString("sheetName");
        Map form = jsonParam.getObject("form", Map.class);
        String timeStart = "", timeEnd = "";
        if (form != null) {
            if (form.get("timeStart") != null) {
                timeStart = (String) form.get("timeStart");
            }
            if (form.get("timeEnd") != null) {
                timeEnd = (String) form.get("timeEnd");
            }
        }
//exportExcel为异步方法，需要在调用处加上@Async注解
        Future<List<CpyScoreExcelEn>> cpyScoreExcelEn = monthlyTrendBu.cpyScoreExcel(fields, filename, ids, isHeader, mode, original, pager, sheetName, token, timeStart, timeEnd, plantId);
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        BorderStyle borderStyle = BorderStyle.THIN;
        short borderColor = IndexedColors.BLACK.getIndex();
        contentWriteCellStyle.setBorderTop(borderStyle);
        contentWriteCellStyle.setBorderBottom(borderStyle);
        contentWriteCellStyle.setBorderLeft(borderStyle);
        contentWriteCellStyle.setBorderRight(borderStyle);
        contentWriteCellStyle.setTopBorderColor(borderColor);
        contentWriteCellStyle.setBottomBorderColor(borderColor);
        contentWriteCellStyle.setLeftBorderColor(borderColor);
        contentWriteCellStyle.setRightBorderColor(borderColor);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(null, contentWriteCellStyle);
//       拿到List<PoundQueryExcelBo> 之后，进行导出
        List<CpyScoreExcelEn> cpyScoreExcelBos = cpyScoreExcelEn.get();
        response.setContentType("application/vnd.ms-excel; charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8") + ".xlsx");
        EasyExcel.write(response.getOutputStream(), CpyScoreExcelEn.class)
                .registerWriteHandler(horizontalCellStyleStrategy)
                .sheet(sheetName)
                .doWrite(cpyScoreExcelBos);
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }
}
